<template>
  <el-card>
    <template #header>
      <div class="title">
        时段柱状图（总）
        <el-tooltip effect="dark" content="点击试试下载" placement="bottom">
          <i-ep-download class="download" @click="downloadEchart" />
        </el-tooltip>
      </div>
    </template>

    <div :id="id" :class="className" :style="{ height, width }"></div>
  </el-card>
</template>

<script setup lang="ts">
import * as echarts from "echarts";
import { onMounted } from 'vue'; 
import { ref } from 'vue';
import { markRaw } from 'vue';
import { onActivated } from 'vue';
import axios from 'axios'; // 引入axios用于发起HTTP请求

axios.defaults.baseURL = 'http://127.0.0.1:8080';
const props = defineProps({
  id: {
    type: String,
    default: "barChart",
  },
  className: {
    type: String,
    default: "",
  },
  width: {
    type: String,
    default: "200px",
    required: true,
  },
  height: {
    type: String,
    default: "200px",
    required: true,
  },
});

const loginData = ref([]); // 使用ref定义响应式变量
const growthRateData = ref([]);



// 定义获取数据的函数  
const fetchData = async () => {  
  try {  
    const response = await axios.get('/back/record/getBarChart11');  
    // const data=[];
    console.log(response.data); 
    if (Array.isArray(response.data)) {  
      loginData.value = response.data;
      console.log(loginData.value[1]); 
      // 计算增长率  
      growthRateData.value = loginData.value.map((value, index) => {  
        if (index === 0) {  
          return 0; // 初始值设为0  
        }  
        const prevValue = loginData.value[index - 1];  
        if (prevValue === 0) {  
          // 如果前一个值是0，避免除以0的错误  
          return null; // 或者你可以返回0，但表示没有增长率  
        }  
        return (((value - prevValue) / prevValue) * 100).toFixed(2); // 计算增长率并保留两位小数  
      });         
      // 更新图表  
      updateChart();  
    } else {  
      console.error('Response data is not an array.');  
    }  
  } catch (error) {  
    console.error('Error fetching data:', error);  
  }  
};  

// 更新图表逻辑  
const updateChart = () => {  
  // 确保chart和options已经被定义和初始化  
  if (chart.value && options) {  
    chart.value.setOption({  
      ...options,  
      series: [  
        {  
          ...options.series[0],  
          data: loginData.value,  
        },  
        // 注意：如果growthRateData中有null值，图表可能无法正确显示  
        // 你可能需要处理这些null值，例如使用undefined、0或其他合适的值代替  
        {  
          ...options.series[1],  
          data: growthRateData.value.filter(rate => rate !== null), // 过滤掉null值（如果有的话）  
        },  
      ],  
    });  
  }  
};  


const options = {
  grid: {
    left: "2%",
    right: "2%",
    bottom: "10%",
    containLabel: true,
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      crossStyle: {
        color: "#999",
      },
    },
  },
  legend: {
    x: "center",
    y: "bottom",
    data: ["登录人数", "人数增长率"],
    textStyle: {
      color: "#999",
    },
  },
  xAxis: [
    {
      type: "category",
      data: ["0-2", "2-4", "4-6", "6-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18-20", "20-22", "22-24"],
      axisPointer: {
        type: "shadow",
      },
    },
  ],
  yAxis: [
    {
      type: "value",
      axisLabel: {
        formatter: "{value}",
      },
    },
    {
      type: "value",
      axisLabel: {
        formatter: "{value}%",
      },
    },
  ],
  series: [
    {
      name: "登录人数",
      type: "bar",
      data: loginData,
      barWidth: 20,
      itemStyle: {
        color: function (params) {
          // 设置柱子颜色交替显示
          const colors = [
            new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#83bff6" },
              { offset: 0.5, color: "#188df0" },
              { offset: 1, color: "#188df0" },
            ]),
            new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#25d73c" },
              { offset: 0.5, color: "#1bc23d" },
              { offset: 1, color: "#179e61" },
            ]),
          ];
          return colors[params.dataIndex % colors.length];
        },
      },
    },
    {
      name: "人数增长率",
      type: "line",
      yAxisIndex: 1, // 使用第二个y轴
      data: growthRateData,
    },
  ],
};

const downloadEchart = () => {
  const img = new Image();
  img.src = chart.value.getDataURL({
    type: "png",
    pixelRatio: 1,
    backgroundColor: "#fff",
  });

  img.onload = () => {
    const canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    const ctx = canvas.getContext("2d");
    if (ctx) {
      ctx.drawImage(img, 0, 0, img.width, img.height);
      const link = document.createElement("a");
      link.download = `时段柱状图.png`;
      link.href = canvas.toDataURL("image/png", 0.9);
      document.body.appendChild(link);
      link.click();
      link.remove();
    }
  };
};

const chart = ref<any>("");
  onMounted(async () => {
  try {
    chart.value = markRaw(
      echarts.init(document.getElementById(props.id) as HTMLDivElement)
    );
    console.log('Chart initialized'); // 添加调试信息
  } catch (error) {
    console.error('Error initializing chart:', error);
  }

  try {
    await fetchData(); // 在组件挂载后获取数据
    console.log('Data fetched and chart updated'); // 添加调试信息
  } catch (error) {
    console.error('Error fetching data or updating chart:', error);
  }

  window.addEventListener("resize", () => {
    if (chart.value) {
      chart.value.resize();
    }
  });
});

onActivated(() => {
  if (chart.value) {
    chart.value.resize();
  }
});
</script>

<style lang="scss" scoped>
.title {
  display: flex;
  justify-content: space-between;

  .download {
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }
}
</style>
